package com.chenjim.glrecorder;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaExtractor;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.chenjim.glrecorder.util.MP4Config;
import com.chenjim.glrecorder.util.UdpSend;
import java.nio.ByteBuffer;


public class VideoDecoderActivity extends AppCompatActivity {

    private final String TAG = "VideoDecoderActivity";
    private SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_decoder);
        surfaceView = findViewById(R.id.surface);

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                //SimpleDecodeVideoPlayer simpleDecodeVideoPlayer = new SimpleDecodeVideoPlayer();
                //simpleDecodeVideoPlayer.init(Environment.getExternalStorageDirectory() + "/1/" + "20240819_08.10.15.mp4", holder.getSurface());
                //new Thread(() -> playbackFile(Environment.getExternalStorageDirectory() + "/1/" + "20240819_08.10.15.mp4")).start();
                /*VideoDecoder mVideoDecoder = new VideoDecoder(surface1);
                mVideoDecoder.setOutputFormat(VideoDecoder.COLOR_FORMAT_NV12); // 设置输出nv12的数据

                // 某某线程中
                mVideoDecoder.decode(, new VideoDecoder.DecodeCallback() {
                    @Override
                    public void onDecode(byte[] yuv, int width, int height, int frameCount, long presentationTimeUs) {
                        Log.d(TAG, "frameCount: " + frameCount + ", presentationTimeUs: " + presentationTimeUs);
                        // yuv数据操作，例如保存或者再去编码等
                    }

                    @Override
                    public void onFinish() {
                        Log.d(TAG, "onFinish");
                    }

                    @Override
                    public void onStop() {
                        Log.d(TAG, "onStop");
                    }
                });*/
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }

    public static final int FRAME_MAX_LEN = 300 * 1024;
    private byte[] frameData;
    private byte[] byte_3 = null;

    private void playbackFile(String name) {
        playbacking = true;
        try {
            int readLen = 0;
            // 解析MP4录像文件的SPS PPS，和I帧一起进行发送
            MP4Config mp4Config = new MP4Config(name);
            byte[] sps = byteMerger1(new byte[]{0, 0, 0, 1}, mp4Config.getSPS());
            byte[] pps = byteMerger1(new byte[]{0, 0, 0, 1}, mp4Config.getPPS());
            byte[] spspps = byteMerger1(sps, pps);

            MediaExtractor extractor = new MediaExtractor();
            extractor.setDataSource(name);
            extractor.selectTrack(0);
            ByteBuffer buffer = ByteBuffer.allocate(FRAME_MAX_LEN);
            while (playbacking && (readLen = extractor.readSampleData(buffer, 0)) >= 0) {
                //rtph264.timestamp = extractor.getSampleTime();
                if (frameData == null) {
                    frameData = new byte[readLen];
                }

                buffer.get(frameData, 0, readLen);
                if (byte_3 == null) {
                    byte_3 = new byte[spspps.length + frameData.length];
                }

                Log.i(TAG, "====> playbackFile" + frameData.length);
                byte[] bytes = byteMerger(spspps, frameData, byte_3);
                UdpSend.getInstance("192.168.5.142").sendPack(bytes);
                /*if (CommonUtils.isIFrame(frameData)) {
                    Log.i(TAG, "====> I" + Arrays.toString(frameData));

                } else {
                    Log.i(TAG, "====> B P" + frameData.length);
                    UdpSend.getInstance("192.168.5.142").sendPack(frameData);
                }*/
                SystemClock.sleep(5);
            }
        } catch (Exception e) {
            Log.e(TAG, "回放文件异常: " + e.getMessage());
        } finally {
            playbackStop();
        }
    }

    public boolean playbackStop() {
        playbacking = false;
        return true;
    }

    protected boolean playbacking = false;

    public byte[] byteMerger1(byte[] byte_1, byte[] byte_2) {
        byte[] bytes = new byte[byte_1.length + byte_2.length];
        System.arraycopy(byte_1, 0, bytes, 0, byte_1.length);
        System.arraycopy(byte_2, 0, bytes, byte_1.length, byte_2.length);
        return bytes;
    }

    public byte[] byteMerger(byte[] byte_1, byte[] byte_2, byte[] byte_3) {
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }

}